<template>
  <!-- 选择图片 -->
  <section class="section">
    <!-- 设置一个按钮 -->
    <a-button class="select-picture" style="width: 120px">
      <template #icon><UploadOutlined /></template>
      <span>{{ result ? '重新选择' : '选择图片' }}</span>
      <input
        ref="uploadInput"
        type="file"
        accept="image/jpg, image/jpeg, image/png, image/gif"
        @change="selectFile"
      />
    </a-button>
    <!-- 设置一个按钮 -->
  </section>
  <!-- 选择图片 -->

  <!-- 结果预览区 -->
  <!-- <section class="section" v-if="result">
    <p>裁切后的Base64图片预览：</p>
    <div class="preview" ref="preview">
      <img :src="result" alt="" />
    </div>
    <p>可以按F12查看打印的base64/blob结果</p>
  </section> -->
  <!-- 结果预览区 -->

  <!-- 用于裁切的弹窗 -->
  <a-modal v-model:visible="isShowDialog" title="图片裁切" width="600px" :maskClosable="false">
    <template #footer>
      <a-button @click="isShowDialog = false">取消</a-button>
      <a-button @click="clear">清除</a-button>
      <a-button @click="reset">重置</a-button>
      <a-button type="primary" :loading="loading" @click="getResult">{{
        loading ? '上传中' : '确定'
      }}</a-button>
    </template>

    <!-- 图片裁切插件 -->
    <vue-picture-cropper
      :key="aspectRatio"
      :boxStyle="{
        width: '100%',
        height: '100%',
        backgroundColor: '#f8f8f8',
        margin: 'auto'
      }"
      :img="pic"
      :options="{
        viewMode: 1,
        dragMode: 'crop',
        aspectRatio,
        preview: preview
      }"
    />
    <!-- 图片裁切插件 -->
  </a-modal>
  <!-- 用于裁切的弹窗 -->
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import VuePictureCropper, { cropper } from 'vue-picture-cropper'
import commonApi from '@/api/common'
export default defineComponent({
  components: {
    VuePictureCropper,
    UploadOutlined
  },
  props: {
    aspectRatio: {
      type: Number,
      default: 1 / 1
    },
    uploadImg: {
      type: String,
      default: 'img'
    }
  },
  emits: ['handle-tailor-success'],
  setup(prop, ctx) {
    console.log('%c 🦑 prop: ', 'font-size:20px;background-color: #FCA650;color:#fff;', prop)
    const uploadInput = ref<any>(null)
    const preview = ref<string>('')
    const pic = ref<string>('')
    const loading = ref<boolean>(false)
    // const picType = ref<string>('')
    const result = ref<string>('')
    // const uploadResult = ref<string>('')
    const isShowDialog = ref<boolean>(false)
    /**
     * 选择图片
     */
    const selectFile = (e: any): void => {
      // 获取选取的文件
      const file: any = e.target.files[0]
      // 转换为base64传给裁切组件
      const reader: any = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (): void => {
        // 更新裁切弹窗的图片源
        pic.value = reader.result
        // 显示裁切弹窗
        isShowDialog.value = true
        // 清空已选择的文件
        uploadInput.value.value = ''
      }
    }
    /**
     * 获取裁切结果
     */
    const getResult = (): void => {
      loading.value = true
      // 获取生成的base64图片地址
      // const DATA_URL: string = cropper.getDataURL()
      // console.log('DATA_URL', DATA_URL)
      // 获取生成的blob文件信息
      const BLOB: any = cropper.getBlob()
      const data = new File([BLOB], 'zxy.png')
      console.log('%c 🎂 data: ', 'font-size:20px;background-color: #7F2B82;color:#fff;', data)
      const fd = new FormData()
      fd.append('fileData', data)
      console.log(
        '%c 🥔 fd: ',
        'font-size:20px;background-color: #42b983;color:#fff;',
        fd.getAll('img')
      )
      // 把base64赋给结果展示区
      // result.value = DATA_URL
      // 隐藏裁切弹窗
      isShowDialog.value = false
      commonApi.uploadFile(fd).then((res) => {
        console.log('%c 🥐 res: ', 'font-size:20px;background-color: #FFDD4D;color:#fff;', res)
        loading.value = false
        if (~~res.code === 500005) {
          message.success('上传成功')
          ctx.emit('handle-tailor-success', res.result.data.path)
        } else {
          message.success('上传失败')
        }
      })
    }
    /**
     * 清除裁切框
     */
    const clear = (): void => {
      cropper.clear()
    }
    /**
     * 重置默认的裁切区域
     */
    const reset = (): void => {
      cropper.reset()
    }
    return {
      // 数据
      uploadInput,
      preview,
      pic,
      result,
      isShowDialog,
      // 方法
      selectFile,
      getResult,
      clear,
      reset,
      loading
    }
  }
})
</script>

<style lang="scss" scoped>
.section {
  display: flex;
  height: 32px;
  margin-left: 20px;
  flex-direction: column;
  align-items: bottom;

  &:last-child {
    margin-bottom: 0;
  }
  // 选图按钮

  .select-picture {
    position: relative;

    input {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
    }
  }
}

// 预览区

.preview {
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: 800px;
  margin-bottom: 1em;
}

img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
</style>
